package com.yunshipei.manager;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

import com.yunshipei.db.green.AppStatisticsDao;
import com.yunshipei.db.green.DaoMaster;
import com.yunshipei.db.green.DaoSession;
import com.yunshipei.db.green.XCloudSignDao;
import com.yunshipei.db.green.YspProxyDao;
import com.yunshipei.utils.EncUtils;
import com.yunshipei.utils.FileUtils;

import java.io.File;

public class EnterDbManager {

    private EnterDbManager() {

    }

    private static final class EnterDbManagerInner {
        private static final EnterDbManager instances = new EnterDbManager();
    }

    public static EnterDbManager getInstances() {
        return EnterDbManagerInner.instances;
    }

    private AppStatisticsDao appStatisticsDao;
    private XCloudSignDao xCloudSignDao;
    private YspProxyDao yspProxyDao;

    private boolean init = false;

    private String key;

    public void init(Context context) {
        if (init) return;
        init = true;
        this.key = context.getSharedPreferences("ysp_rongCloud", Activity.MODE_PRIVATE).getString("uuid", "");
        String path = Environment.getDataDirectory() + "/data/" + context.getPackageName() + "/extra/";
        FileUtils.makeRootDirectory(path);
        File file = new File(path, "app-enter");
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, file.getAbsolutePath(), null) {
            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                //数据库升级
                for (int i = oldVersion; i < newVersion; i++) {
                    switch (i) {
                        case 1:
                            XCloudSignDao.createTable(db, true);
                            break;
                        case 2:
                            update2EncData(db);
                            break;
                        case 3:
                            updateStatisticsTab(db);
                            break;
                        case 4:
                            YspProxyDao.createTable(db, true);
                            break;
                    }
                }
            }
        };
        SQLiteDatabase db = helper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        DaoSession daoSession = daoMaster.newSession();
        appStatisticsDao = daoSession.getAppStatisticsDao();
        xCloudSignDao = daoSession.getXCloudSignDao();
        yspProxyDao = daoSession.getYspProxyDao();
    }

    //版本四增加departmentId
    private void updateStatisticsTab(SQLiteDatabase db) {
        AppStatisticsDao.dropTable(db, true);
        AppStatisticsDao.createTable(db, true);
    }

    //未加密用户名密码，加密保存
    private void update2EncData(SQLiteDatabase db) {
        String tabName = XCloudSignDao.TABLENAME;
        String user_host = XCloudSignDao.Properties.Host.columnName;
        String user_name = XCloudSignDao.Properties.UserName.columnName;
        String user_pass = XCloudSignDao.Properties.Password.columnName;
        Cursor cursor = db.query(tabName, null, null, null, null, null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                String host = cursor.getString(cursor.getColumnIndex(user_host));
                String userName = cursor.getString(cursor.getColumnIndex(user_name));
                String password = cursor.getString(cursor.getColumnIndex(user_pass));
                String encUserName = EncUtils.encrypt(key, userName.getBytes());
                String encPassword = EncUtils.encrypt(key, password.getBytes());
                ContentValues contentValues = new ContentValues();
                contentValues.put(user_name, encUserName);
                contentValues.put(user_pass, encPassword);
                db.update(tabName, contentValues, user_host + "=?", new String[]{host});
            }
            cursor.close();
        }
    }

    public AppStatisticsDao getAppStatisticsDao() {
        return appStatisticsDao;
    }

    public XCloudSignDao getXCloudSignDao() {
        return xCloudSignDao;
    }

    public YspProxyDao getYspProxyDao() {
        return yspProxyDao;
    }

    private void clearXCloudSign() {
        try {
            if (xCloudSignDao != null) {
                xCloudSignDao.deleteAll();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void clearYspProxy() {
        try {
            if (yspProxyDao != null) {
                yspProxyDao.deleteAll();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //删除存储的相关数据，埋点统计的数据不删除，保证数据能完整上传上去
    public void delete() {
        clearXCloudSign();
        clearYspProxy();
    }
}
